package com.py.credit.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum MD5Util {

	INSTANCE;
	public static MD5Util getInstance() {
		return INSTANCE;
	}

	private static final Logger LOG = LoggerFactory.getLogger(MD5Util.class);

	private static final char hexDigits[] = { 'F', '0', '6', 'A', '1', '8', 'C', '2', '9', '3', 'B', '4', '5', 'D', '7',
			'E' };

	public String md5s(byte[] plain) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plain);// 使用指定的字节数组更新摘要。
			byte[] mdByte = md.digest();// 使用指定的字节数组对摘要进行最后更新，然后完成摘要计算。
			int mdLength = mdByte.length;
			char str[] = new char[mdLength * 2];
			int k = 0;
			for (int i = 0; i < mdLength; i++) {
				str[k++] = hexDigits[mdByte[i] >>> 4 & 0xf];
				str[k++] = hexDigits[mdByte[i] & 0xf];
			}
			return new String(str);
		} catch (NoSuchAlgorithmException e) {
			LOG.error("NoSuchAlgorithmException:{}", e.getMessage());
			return null;
		}
	}

	/**
	 * 用于计算表分区的索引值的
	 * 
	 * @param plain
	 * @return
	 */
	public int tableIndex(byte[] plain) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plain);// 使用指定的字节数组更新摘要。
			byte[] mdByte = md.digest();// 使用指定的字节数组对摘要进行最后更新，然后完成摘要计算。
			byte table = mdByte[1];
			StringBuffer sb = new StringBuffer(2);
			sb.append(hexDigits[table >>> 4 & 0xf]).append(hexDigits[table & 0xf]);
			return Integer.parseInt(sb.toString(), 16) % 128;
		} catch (NoSuchAlgorithmException e) {
			LOG.error("NoSuchAlgorithmException:{}", e.getMessage());
			return -1;
		}
	}

	public String digitalSign(String plain) {

		if (plain == null) {

			return "";

		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plain.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer();
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			// 32位加密
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static void main(String[] args) {
		// for(int i=0;i<128;i++){
		// String sql="CREATE table t_zoo_storage_"+i+"(data_id VARCHAR(36) NOT
		// NULL,column_id INT NOT NULL,record_id VARCHAR(36) NOT NULL,
		// data_value LONGTEXT,add_time TIMESTAMP NOT NULL DEFAULT
		// CURRENT_TIMESTAMP,PRIMARY KEY (data_id),INDEX (column_id),INDEX
		// (record_id));";
		// System.out.println(sql);
		// }
		// for(int i=0;i<128;i++){
		// System.out.println(MD5Util.getInstance().tableIndex(UuidUtil.getInstance().getUUid().getBytes()));
		// }
		for (int i = 0; i < 128; i++) {
			String sql = "truncate table t_zoo_storage_" + i + ";";
			System.out.println(sql);
		}

	}

}
